<script lang="ts" setup>
import type { Recordable } from '@vben/types';

import type {
  VxeGridListeners,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { RoleApi } from '#/api/types';

import { ref } from 'vue';

import { Page } from '@vben/common-ui';
import { Plus } from '@vben/icons';

import { Button, message, Modal } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  batchDeleteRolesApi,
  deleteRoleApi,
  getRoleListApi,
  updateRoleStatusApi,
} from '#/api/core/modules/role';
import { $t } from '#/locales';

import CreateForm from './modules/create-form.vue';
import EditForm from './modules/edit-form.vue';
import MenuAssign from './modules/menu-assign.vue';
import PermissionAssign from './modules/permission-assign.vue';

// 创建角色抽屉引用
const createFormRef = ref();

// 编辑角色抽屉引用
const editFormRef = ref();

// 权限分配抽屉引用
const permissionAssignRef = ref();

// 菜单分配抽屉引用
const menuAssignRef = ref();

// 存储选中的行数据
const selectedRows = ref<RoleApi.RoleVO[]>([]);

// 表格事件监听
const gridEvents: VxeGridListeners<RoleApi.RoleVO> = {
  checkboxAll: onSelectionChange,
  checkboxChange: onSelectionChange,
};

// 表格组件
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    collapsed: true,
    submitOnChange: true,
    schema: [
      {
        component: 'Input',
        fieldName: 'name',
        label: $t('system.role.roleName'),
      },
      {
        component: 'Input',
        fieldName: 'code',
        label: $t('system.role.code'),
      },
      {
        component: 'Select',
        componentProps: {
          allowClear: true,
          options: [
            { label: $t('common.enabled'), value: 1 },
            { label: $t('common.disabled'), value: 0 },
          ],
        },
        fieldName: 'status',
        label: $t('system.role.status'),
      },
    ],
  },
  gridEvents,
  gridOptions: {
    columns: [
      {
        field: 'id',
        width: 50,
        type: 'checkbox',
      },
      {
        field: 'name',
        title: $t('system.role.roleName'),
        width: 150,
      },
      {
        field: 'code',
        title: $t('system.role.code'),
        width: 150,
      },
      {
        field: 'description',
        title: $t('system.role.remark'),
        width: 200,
      },
      {
        cellRender: {
          attrs: { beforeChange: onStatusChange },
          name: 'CellSwitch',
        },
        field: 'status',
        title: $t('system.role.status'),
        width: 100,
      },
      {
        field: 'sort',
        title: $t('system.role.sort'),
        width: 80,
      },
      {
        field: 'createdTime',
        title: $t('system.role.createTime'),
        width: 180,
      },
      {
        align: 'center',
        cellRender: {
          attrs: {
            nameField: 'name',
            nameTitle: $t('system.role.name'),
            actions: [
              {
                code: 'edit',
                name: $t('ui.actionTitle.edit', [$t('system.role.name')]),
              },
              { code: 'permission', name: $t('system.role.setPermissions') },
              { code: 'menu', name: $t('system.role.setMenus') },
              {
                code: 'delete',
                name: $t('ui.actionTitle.delete', [$t('system.role.name')]),
              },
            ],
            onClick: onActionClick,
          },
          name: 'CellOperation',
        },
        field: 'operation',
        fixed: 'right',
        title: $t('ui.table.action'),
      },
    ],
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          const result = await getRoleListApi({
            current: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
          return result.data;
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      custom: true,
      export: false,
      refresh: { code: 'query' },
      search: true,
      zoom: true,
    },
    checkboxConfig: {
      checkField: 'checked',
      checkStrictly: false,
      highlight: true,
    },
  } as VxeTableGridOptions<RoleApi.RoleVO>,
});

// 监听选择变化事件
function onSelectionChange(params: {
  checked: boolean;
  records: RoleApi.RoleVO[];
}) {
  const rows = params.records;
  selectedRows.value = rows || [];
}

// 操作按钮点击处理
function onActionClick(e: { code: string; row: RoleApi.RoleVO }) {
  switch (e.code) {
    case 'delete': {
      onDelete(e.row);
      break;
    }
    case 'edit': {
      onEdit(e.row);
      break;
    }
    case 'menu': {
      onMenuAssign(e.row);
      break;
    }
    case 'permission': {
      onPermissionAssign(e.row);
      break;
    }
  }
}

// 确认弹窗
function confirm(content: string, title: string) {
  return new Promise((resolve, reject) => {
    Modal.confirm({
      content,
      onCancel() {
        reject(new Error('已取消'));
      },
      onOk() {
        resolve(true);
      },
      title,
    });
  });
}

// 处理状态切换
async function onStatusChange(newStatus: number, row: RoleApi.RoleVO) {
  const status: Recordable<string> = {
    0: $t('common.disabled'),
    1: $t('common.enabled'),
  };
  try {
    await confirm(
      $t('ui.confirmMessage.changeStatus', [
        row.name,
        status[newStatus.toString()],
      ]),
      $t('ui.actionTitle.changeStatus'),
    );
    await updateRoleStatusApi({ roleId: row.id, status: newStatus });
    return true;
  } catch {
    return false;
  }
}

// 编辑角色
function onEdit(row: RoleApi.RoleVO) {
  // 调用编辑表单抽屉的API打开并传递数据
  editFormRef.value.drawerApi.setData(row).open();
}

// 删除角色
function onDelete(row: RoleApi.RoleVO) {
  Modal.confirm({
    title: $t('ui.actionTitle.delete', [$t('system.role.name')]),
    content: $t('ui.confirmMessage.delete', [row.name]),
    okText: $t('common.confirm'),
    cancelText: $t('common.cancel'),
    okType: 'danger',
    async onOk() {
      const hideLoading = message.loading({
        content: $t('ui.actionMessage.deleting', [row.name]),
        duration: 0,
        key: 'action_process_msg',
      });

      try {
        const result = await deleteRoleApi(row.id);
        if (result.success) {
          message.success({
            content: $t('ui.actionMessage.deleteSuccess', [row.name]),
            key: 'action_process_msg',
          });
        } else {
          message.warning(result.message);
        }
        onRefresh();
      } catch {
        message.error({
          content: $t('common.operationFailed'),
          key: 'action_process_msg',
        });
      } finally {
        hideLoading();
      }
    },
  });
}

// 分配权限
function onPermissionAssign(row: RoleApi.RoleVO) {
  permissionAssignRef.value.drawerApi.setData(row).open();
}

// 分配菜单
function onMenuAssign(row: RoleApi.RoleVO) {
  menuAssignRef.value.drawerApi.setData(row).open();
}

// 刷新表格
function onRefresh() {
  // 刷新时清空选中状态
  selectedRows.value = [];
  // 调用表格刷新
  gridApi.query();
}

// 创建角色
function onCreate() {
  // 打开创建角色抽屉
  createFormRef.value.drawerApi.open();
}

// 批量删除角色
async function onBatchDelete() {
  if (!selectedRows.value || selectedRows.value.length === 0) {
    message.warning(
      $t('ui.actionMessage.pleaseSelect', [$t('system.role.name')]),
    );
    return;
  }

  Modal.confirm({
    title: $t('ui.actionTitle.batchDelete', [$t('system.role.name')]),
    content: $t('ui.confirmMessage.batchDelete', [
      selectedRows.value.length,
      $t('system.role.name'),
    ]),
    okText: $t('common.confirm'),
    cancelText: $t('common.cancel'),
    okType: 'danger',
    async onOk() {
      const hideLoading = message.loading({
        content: $t('ui.actionMessage.batchDeleting', [$t('system.role.name')]),
        duration: 0,
        key: 'batch_delete_msg',
      });

      try {
        // 提取角色ID数组
        const roleIds = selectedRows.value.map((row) => row.id);

        // 调用批量删除API
        const result = await batchDeleteRolesApi(roleIds);
        if (result.success) {
          message.success({
            content: $t('ui.actionMessage.batchDeleteSuccess'),
            key: 'batch_delete_msg',
          });
          // 清空选中的行
          selectedRows.value = [];
          // 刷新表格
          onRefresh();
        } else {
          message.warning(result.message);
        }
      } catch {
        message.error({
          content: $t('common.operationFailed'),
          key: 'batch_delete_msg',
        });
      } finally {
        hideLoading();
      }
    },
  });
}
</script>
<template>
  <Page auto-content-height>
    <CreateForm ref="createFormRef" @success="onRefresh" />
    <EditForm ref="editFormRef" @success="onRefresh" />
    <PermissionAssign ref="permissionAssignRef" @success="onRefresh" />
    <MenuAssign ref="menuAssignRef" @success="onRefresh" />
    <Grid :table-title="$t('system.role.list')">
      <template #toolbar-tools>
        <Button type="primary" @click="onCreate">
          <Plus class="size-5" />
          {{ $t('ui.actionTitle.create', [$t('system.role.name')]) }}
        </Button>
        <Button danger @click="onBatchDelete" class="ml-2">
          {{ $t('ui.actionTitle.batchDelete', [$t('system.role.name')]) }}
        </Button>
      </template>
    </Grid>
  </Page>
</template>
